import { ForbiddenException, Injectable, Query } from '@nestjs/common';
import { CreateTimeSlotDto } from './dto/create-time-slot.dto';
import { UpdateTimeSlotDto } from './dto/update-time-slot.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { TimeSlot } from './entities/time-slot.entity';
import { In, Repository } from 'typeorm';

@Injectable()
export class TimeSlotsService {
  constructor(
    @InjectRepository(TimeSlot)
    private timeSlotRepository: Repository<TimeSlot>,
  ) {}

  create(createTimeSlotDto: CreateTimeSlotDto) {
    return this.timeSlotRepository.save(createTimeSlotDto);
  }

  findAll() {
    return this.timeSlotRepository.find();
  }

  findOne(id: number) {
    return this.timeSlotRepository.findOne({ where: { timeSlot_id: id } });
  }

  async update(id: number, updateTimeSlotDto: UpdateTimeSlotDto) {
    const res = await this.findOne(id);
    if (!res.timeSlot_id) {
      throw new ForbiddenException('更新失败');
    }
    const newRes = this.timeSlotRepository.merge(res, updateTimeSlotDto);
    return this.timeSlotRepository.save(newRes);
  }

  async remove(id: number) {
    const res = await this.findOne(id);
    if (res.timeSlot_id) {
      return this.timeSlotRepository.remove(res);
    }
    throw new ForbiddenException('删除失败');
  }

  // 返回实体
  async returnTimeSlotsEntities(ids: number[]) {
    return await this.timeSlotRepository.find({
      where: {
        timeSlot_id: In(ids),
      },
    });
  }
}
